import React, { useState } from "react";
import { ArrowUpOutlined, LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Checkbox, Form, Input, message } from "antd";
import styles from "./index.module.scss";
import { localStorageSetItem } from "@/utils/localStorage";
import { useNavigate, Link } from "react-router-dom";
import Cookie from "js-cookie";
import baseUrl from '@/config';
import { useEffect } from "react";

const formData = {
  username: "admin",
  password: "123456",
};

const App: React.FC = () => {
  const navigateTo = useNavigate();
  const { loginFormBox, loginFormButton, formTitle } = styles;
  const [loadings, setLoadings] = useState<boolean[]>([]);
  const [verifyCode, setVerifyCode] = useState('');

  useEffect(() => {
    message.success("wx小程序演示地如下，可选择复制：https://wxbike.crzzx.xyz/",3)
  }, []);

  const handleVerifyCode = (event: { target: { value: React.SetStateAction<string>; }; }) => {
    setVerifyCode(event.target.value);
  };

  // 处理登录
  const postData = async (account: any, pwd: any) => {
    setLoadings([true]);
    try {
      const response = await fetch(baseUrl + '/back/user/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ account, pwd })
      });

      if (response.ok) {
        // 请求成功
        const data = await response.json();
        // 处理响应数据
        if (data.msg === '登录成功') {
          const token = data.data.token;
          const userId = data.data.userId;
          const userName = data.data.userName;
          Cookie.set("token", token);
          localStorageSetItem("userId", userId);
          localStorageSetItem("userName", userName);

          message.success('登录成功！', 2)
          setTimeout(() => {
            navigateTo("/");
          }, 500);
        }
        else {
          message.warning(data.msg, 2)
        }
      } else {
        // 请求失败
        console.error('Error:', response.status);
      }
    } catch (error) {
      console.error('Error:', error);
    }
    setLoadings([false]);
  };

  const [nextCode, setNextCode] = useState(baseUrl + "/sys/verify/getVerify")

  const getNextCode = () => {
    // 为了使每次请求都是不同的 URL，可以在 URL 后添加一个随机参数
    const randomParam = Math.random().toString(36).substring(7);
    setNextCode(`${baseUrl}/sys/verify/getVerify?${randomParam}`);
  }

  const onFinish = async (values: any) => {
    console.log("Received values of form: ", values);
    // 首先校验一下验证码是否正确
    try {
      const response = await fetch(baseUrl + '/sys/verify/checkVerify?verifyInput=' + verifyCode, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (response.ok) {
        // 请求成功
        const data = await response.json();
        // 处理响应数据
        if (data.code == 200) {
          localStorageSetItem("userInfo", values);
          postData(values.username, values.password);
        }
        else {
          message.warning(data.msg, 2)
        }
      } else {
        // 请求失败
        console.error('Error:', response.status);
      }
    } catch (error) {
      console.error('Error:', error);
    }
  };

  return (
    <div className={`${loginFormBox} global-center`}>
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{ remember: true }}
        onFinish={onFinish}
      >
        <h1 className={`${formTitle} global-center`}>智淬单车</h1>
        <h1 className={`${formTitle} global-center`}>
          智能调度平台后台管理系统
        </h1>
        <Form.Item
          name="username"
          rules={[{ required: true, message: "请填写账号！" }]}
          initialValue={formData.username}
        >
          <Input
            prefix={<UserOutlined className="site-form-item-icon" />}
            placeholder="账号"
          />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: "请填写密码！" }]}
          initialValue={formData.password}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="密码"
          />
        </Form.Item>
        <img src={nextCode} onClick={getNextCode}></img>
        <Form.Item
          name="verifyCode"
          rules={[{ required: true, message: "请填写验证码！" }]}
        >
          <Input
            prefix={<ArrowUpOutlined className="site-form-item-icon" />}
            placeholder="请输入验证码"
            value={verifyCode}
            onChange={handleVerifyCode}
          />
        </Form.Item>
        <Form.Item>
          <div
            className="global-center"
            style={{ justifyContent: "space-between" }}
          >
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>记住账号密码</Checkbox>
            </Form.Item>

            <Link className="login-form-forgot" to="/findpwd">忘记密码？</Link>

          </div>
        </Form.Item>

        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            className={loginFormButton}
            loading={loadings[0]}
          >
            登录
          </Button>

          <span style={{ float: 'right' }}>
            Or <Link to="/register">现在注册</Link>
          </span>
        </Form.Item>
      </Form>
    </div>
  );
};

export default App;
